const { login, getCardPic } = require('./spider.js');
const { walkData } = require('../data.js');
const { variation } = require('../cardNode.js');

const getDeck = async () => {
  await login();

  const deck = `
  #created by ...
  #main
  81823360
  81823360
  81823360
  18940556
  18940556
  18940556
  80701178
  80701178
  95492061
  95492061
  95492061
  53303460
  53303460
  16229315
  16229315
  55410871
  55410871
  55410871
  18144507
  31036355
  38179121
  38179121
  38179121
  49238328
  49238328
  57995165
  57995165
  57995165
  64697431
  64697431
  46052429
  46052429
  46052429
  24224830
  24224830
  26773909
  26773909
  23002292
  23002292
  23002292
  #extra
  10817524
  80532587
  80532587
  80532587
  74586817
  79606837
  79606837
  79606837
  74294676
  42752141
  48739166
  581014
  12014404
  1482001
  1482001
  !side
  80701178
  85138716
  85138716
  53303460
  23434538
  23434538
  12580477
  31036355
  31036355
  49238328
  24224830
  40838625
  41420027
  41420027
  
  `;

  const list = Array.from(new Set(deck.match(/\d+/g)));
  const errlist = [];

  for (let i = 0; i < list.length; i += 1) {
    const id = list[i];

    try {
      await getCardPic(id, i + 1, list.length);
    } catch {
      errlist.push(id);
    }
  }

  console.log(`\n成功${list.length - errlist.length}个,失败${errlist.length}个`);
  console.log(`失败列表为`, errlist);
};

const getAll = async () => {
  await login();

  const errlist = [];

  let walker = walkData();
  let index = 0;

  const next = () => {
    const res = walker.next();
  
    if (res.done) {
      console.log(`\n成功${list.length - errlist.length}个,失败${errlist.length}个`);
      console.log(`失败列表为`, errlist);
      return;
    }

    res.then(async (data) => {
      index += 1;

      try {
        await getCardPic(variation(data.value), index, '???');
      } catch {
        errlist.push(data.value.id);
      } finally {
        next();
      }
    })
  };

  next();
};

getAll();
